

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class Client implements NetworkEventListener, NetworkInterface {
	Registry registry;
	TicTacRemoteInterface serverRIObject;
	TicTacRemoteInterface myRIObject;
	int myPort;
	Game game;
	
	public Client(String address, int port, int myPort, Game game){
		this.game = game;
		System.setSecurityManager(new LiberalSecurityManager());
		connect2Server(address, port);
		bindMyRIObjectToRegistry();
		askServer2FetchMyObject();
	}
	
	private void bindMyRIObjectToRegistry(){
		myRIObject = TicTacRemoteObject.createTicTacRIObject("clientObj", this);
		try {
			System.out.println("Trying to place a object on registry");
			TicTacRemoteInterface stub = (TicTacRemoteInterface) UnicastRemoteObject.exportObject(myRIObject, myPort);
			
			registry.rebind(myRIObject.myId(), stub);
			System.out.println("Successfully placed an object on registry");
		} catch (RemoteException e) {
			System.out.println("Could not place object on registry");
			e.printStackTrace();
		}
	}
	
	private void askServer2FetchMyObject(){
		try {
			System.out.println("Trying to contact server");
			serverRIObject.fetchMe(myRIObject.myId());
			System.out.println("Contact was made");
		} catch (RemoteException e) {
			System.out.println("The server did not catch it");
			e.printStackTrace();
		}
	}
	
	public RemoteInterface getRIObject(){
		return serverRIObject;
	}
	
	private void connect2Server(String address, int port){
		try {
			connect2ServerLogic(address, port);
		} catch (RemoteException e) {
			System.out.println("Wrong host maybe?");
			e.printStackTrace();
		} 
	
	}
	private void connect2ServerLogic(String address, int port) throws RemoteException{
		System.out.println("Trying to connect to "+address+":"+port);
		registry = LocateRegistry.getRegistry(address, port);
		System.out.println("Registry located.");
		serverRIObject = (TicTacRemoteInterface) RemoteObject.lookupRIObject("serverObj", registry);
		System.out.println("Server Object Located");
	}

	@Override
	public void event(NetworkEvent event) {
		System.out.println("Event was triggered");
		if (event instanceof MoveEvent){
			System.out.println("\t Type: MoveEvent");
			int row = ((MoveEvent) event).getRow();
			int col = ((MoveEvent) event).getCol();
			game.placeMark(row, col);
		}
		else if (event instanceof DisconnectEvent){
			System.out.println("\t Type: DisconnectEvent");
			// TODO Logics for ending game
		}
		
	}

	@Override
	public void doMove(int row, int column) {
		try {
			System.out.println("Trying to send move("+row+", "+column+")...");
			serverRIObject.receivedMove(row, column);
			System.out.println("Move successfully sendt");
		} catch (RemoteException e) {
			System.out.println("Could not send move");
			e.printStackTrace();
		}
		
	}

	@Override
	public void disconnect() {
		// TODO Auto-generated method stub
		
	}
}
